package cn.stylefeng.guns.modular.basic.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.db.Page;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.*;
import cn.stylefeng.guns.modular.basic.model.result.*;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.sys.modular.system.entity.Role;
import cn.stylefeng.guns.sys.modular.system.service.RoleService;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.annotion.Permission;
import cn.stylefeng.guns.core.util.MapUtils;
import cn.stylefeng.guns.core.util.QRCodeUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicUnitCode;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsParam;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicUnitCodeParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsResult;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicUnitCodeResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicUnitCodeService;
import cn.stylefeng.guns.sys.modular.system.entity.Dict;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.DictTypeService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;


/**
 * 收货单位表控制器
 */
@Controller
@RequestMapping("/basicPutgoods")
public class BasicPutgoodsController extends BaseController {

    private String PREFIX = "/basic/basicPutgoods";

    @Autowired
    private BasicPutgoodsService basicPutgoodsService;

    @Autowired
    private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private BasicCarrierService basicCarrierService;

    @Autowired
    private BasicCustomerService basicCustomerService;

    @Autowired
    private DictService dictService;

    @Autowired
    private DictTypeService dictTypeService;

    @Autowired
    private BasicOperateService basicOperateService;
	@Autowired
	private  WarehouseStoreService warehouseStoreService;

	@Autowired
	private BasicWarehouseService warehouseService;
    /**
     * 跳转到主页面
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
    	model.addAttribute("dictlist", dictService.findByDicttypeCode2("COMPANY_TYPE"));
        return PREFIX + "/basicPutgoods.html";
    }

    @RequestMapping("/toqrCode")
    public String toqrCode() {
        return PREFIX + "/qrCode.html";
    }

    /**
     * 创建二维码
     */	
    @RequestMapping(value = "/getqrcode", method = RequestMethod.GET)
    @ResponseBody
    public void generateQRCode4Product(Integer id,String name, HttpServletRequest request, HttpServletResponse response) {
    	User user = userService.getcurrentUser();
    	BasicOperateParam param = new BasicOperateParam();
    	param.setDeptId(user.getDeptId());
    	BasicOperateResult basicOperateResult = basicOperateService.findBySpec(param,user.getOperateId());
    	if(basicOperateResult != null) {
    		id = basicOperateResult.getId();
    		try {
    			//logo
    			File logoFile = new File("");
    			
    			String url = "https://jilu56it.top//unit_register?operateId="+id;
    			
    			QRCodeUtil.drawLogoQRCode(logoFile, url, name,350,350,request,response);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
    /**
     * 跳转到主页面
     */
    @RequestMapping("index_hx")
    public String index_hx() {
        return PREFIX + "/basicPutgoods_hx.html";
    }
	/**
     * 跳转到仓库关联门店页面
     */
    @RequestMapping("index_clm")
    public String index_clm() {
        return PREFIX + "/index_clm.html";
    }
	/**
     * 跳转到门店关联仓库页面
     */
    @RequestMapping("index_mlc")
    public String index_mlc() {
        return PREFIX + "/index_mlc.html";
    }
    
    /**
     * 选择单位页面
     */
    @RequestMapping("tochoiceBasicPutgoods_hx")
    public String tochoiceBasicPutgoods_hx() {
        return PREFIX + "/choiceBasicPutgoods_hx.html";
    }

    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
    	model.addAttribute("dictlist", dictService.findByDicttypeCode2("COMPANY_TYPE"));
    	model.addAttribute("carefullist", dictService.findByDicttypeCode2("CARE_LUL"));
        return PREFIX + "/basicPutgoods_add.html";
    }

    /**
     * 新增页面
     */
    @RequestMapping("/add_hx")
    public String add_hx(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/basicPutgoods_add_hx.html";
    }

    /**
     * 编辑页面
     */
    @RequestMapping("/edit")
    public String edit(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
    	model.addAttribute("dictlist", dictService.findByDicttypeCode2("COMPANY_TYPE"));
    	model.addAttribute("carefullist", dictService.findByDicttypeCode2("CARE_LUL"));
        return PREFIX + "/basicPutgoods_edit.html";
    }

    @Autowired
    private HxBasicUnitCodeService hxBasicUnitCodeService;

    /**
     * 编辑页面
     */
    @RequestMapping("/edit_hx")
    public String edit_hx(BasicPutgoodsParam basicPutgoodsParam,Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
    	BasicPutgoods basicPutgoods = basicPutgoodsService.getById(basicPutgoodsParam.getId());
    	String dictname = "";
    	if(basicPutgoods.getDictId() != null && !basicPutgoods.getDictId().equals(0l)) {
    		HxBasicUnitCode dict = hxBasicUnitCodeService.getById(basicPutgoods.getDictId());
    		if(dict != null) {
    			dictname = dict.getCodeName();
    		}
    	}
    	model.addAttribute("dictname", dictname);
        return PREFIX + "/basicPutgoods_edit_hx.html";
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/import.html";
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcelupdate")
    public String toimportExcelupdate(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/importupdate.html";
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcelhx")
    public String toimportExcelhx(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/importhx.html";
    }

    /**
     * 拉取新零帮门店页面
     */
    @RequestMapping("/topullxlbStore")
    public String topullxlbStore(Model model) {
    	User user = userService.getcurrentUser();
    	//查询可选择客户
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/pullxlbStore.html";
    }

    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    /**
     * 拉取门店
     * @author zhucx
     * @Date 2024-04-17
     */
    @RequestMapping("/pullxlbStore")
    @ResponseBody
    public ResponseData pullxlbStore(String modified_begin, Integer putgoodsCustomerId) {
    	User user = userService.getcurrentUser();
//        String url = "https://test-api.xlbsoft.com/api/hxl.open.store.find";
        String url = "https://hxl-api.xlbsoft.com/api/hxl.open.store.find";
        BasicCustomer r = basicCustomerService.getById(putgoodsCustomerId);

        if(ToolUtil.isEmpty(r.getStoreIdXlb())) {
    		return ResponseData.error("Please maintain the new LingBang shipping store ID");
        }
        if(ToolUtil.isEmpty(r.getGsnumber())) {
    		return ResponseData.error("Please maintain the new LingBang company number");
        }

		BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
		oauth2tokenParam.setDeliverId(r.getDeliverId());
		oauth2tokenParam.setGsnumber(r.getGsnumber());
		BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);
		if(oauth2tokenResult != null) {
			if(ToolUtil.isNotEmpty(oauth2tokenResult.getOauth2TokenXlb())) {
				JSONObject json = new JSONObject();
				json.put("upstream_center_id", r.getStoreIdXlb());
				json.put("update_time", modified_begin);
				String post = HttpRequest.post(url)
							.header("Authorization","bearer "+oauth2tokenResult.getOauth2TokenXlb())
							.body(json.toString()).execute().body();
//				System.out.println("================json："+json+"========================");
//				System.out.println("================post："+post+"========================");
		    	JSONObject jsonObject = new JSONObject(post);
				if(jsonObject.get("code").toString().equals("0")) {
					Map<String, BasicPutgoodsResult> putgoodsMap = new HashMap<>();
					BasicPutgoodsParam hxgoodsp = new BasicPutgoodsParam();
					hxgoodsp.setPutgoodsCustomerId(putgoodsCustomerId);
					List<BasicPutgoodsResult> hxp = basicPutgoodsService.findListBySpec(hxgoodsp,null);
					for (BasicPutgoodsResult pr : hxp) {
						putgoodsMap.put(pr.getPutgoodsName(), pr);
					}
					
					Map<String, HxBasicUnitCodeResult> unitCodeMap = new HashMap<>();
					HxBasicUnitCodeParam unitCodep = new HxBasicUnitCodeParam();
					unitCodep.setV1("门店");
					unitCodep.setDeptId(user.getDeptId());
					unitCodep.setOperateId(user.getOperateId());
					List<HxBasicUnitCodeResult> hxuc = hxBasicUnitCodeService.findListBySpec(unitCodep);
					for (HxBasicUnitCodeResult pr : hxuc) {
						if(ToolUtil.isNotEmpty(pr.getXlbStoreGroupId())) {
							unitCodeMap.put(pr.getXlbStoreGroupId(), pr);
						}
					}
					
					JSONArray jsonArray = new JSONArray(jsonObject.get("data").toString());
					for (Object object : jsonArray) {
						JSONObject jsonObject2 = new JSONObject(object.toString());
						
			            BasicPutgoods bd = new BasicPutgoods();
			            BasicAddressParam bd2 = new BasicAddressParam();
			            bd.setDeliverId(user.getDeliverId());
			            bd.setDeptId(user.getDeptId());
			            bd.setPutgoodsCustomerId(putgoodsCustomerId);
			            bd.setPutgoodsOperateName(r.getCustomerName());
				    	
						String id = jsonObject2.get("id").toString();
						if (ToolUtil.isNotEmpty(id)&&!id.equals("null")) {//id
							bd.setXlbClientId(id);
						} 
				    	
						String name = jsonObject2.get("name").toString();
						if (ToolUtil.isNotEmpty(name)&&!name.equals("null")) {//名称
							bd.setPutgoodsName(name);
						} 
				    	
						String store_group_id = jsonObject2.get("store_group_id").toString();
						if (ToolUtil.isNotEmpty(store_group_id)&&!store_group_id.equals("null")) {//门店分组id
							if(store_group_id.equals("0")) {
	    						bd.setDictId(0l);
							} else {
								HxBasicUnitCodeResult  codeResult = unitCodeMap.get(store_group_id);
								if(codeResult != null) {
									bd.setDictId(Long.parseLong(codeResult.getId()+""));
								}
							}
						} 
				    	
						String address = jsonObject2.get("address").toString();
						if (ToolUtil.isNotEmpty(address)&&!address.equals("null")) {//地址
							bd2.setAddress(address);
						} else {
							bd2.setAddress(name);
						}
				    	
						String tel = jsonObject2.get("tel").toString();
						if (ToolUtil.isNotEmpty(tel)&&!tel.equals("null")) {//电话
							bd2.setTel(tel);
						} 
				    	
						String contact = jsonObject2.get("contact").toString();
						if (ToolUtil.isNotEmpty(contact)&&!contact.equals("null")) {//联系人
							bd2.setContacts(contact);
						} 
				    	
						String province = jsonObject2.get("province").toString();
						if (ToolUtil.isNotEmpty(province)&&!province.equals("null")) {//省
							bd2.setSheng(province);
						} 
				    	
						String city = jsonObject2.get("city").toString();
						if (ToolUtil.isNotEmpty(city)&&!city.equals("null")) {//市
							bd2.setShi(city);
						} 
				    	
						String district = jsonObject2.get("district").toString();
						if (ToolUtil.isNotEmpty(district)&&!district.equals("null")) {//区
							bd2.setQu(district);
						} 
				    	
						String street = jsonObject2.get("street").toString();
						if (ToolUtil.isNotEmpty(street)&&!street.equals("null")) {//街道
							bd2.setJie(street);
						} 
						
						BasicPutgoodsResult  basicPutgoods = putgoodsMap.get(name);
						if(basicPutgoods != null) {
							bd.setId(basicPutgoods.getId());
							basicPutgoodsService.updateById(bd);

			                bd2.setPutgoodsId(Long.parseLong(basicPutgoods.getId().toString()));
				            BasicAddressParam bd3 = new BasicAddressParam();
			                bd3.setPutgoodsId(Long.parseLong(basicPutgoods.getId().toString()));
			                BasicAddressResult addressResult = basicAddressService.findBySpec(bd3);
			                if (addressResult == null) {
			                	bd2.setPutgoodsName(name);
		                    	bd2.setLongitude("0");
		                        bd2.setLatitude("0");
			                    bd2.setSwitchWl("1");
			                    bd2.setSwitchBj("1500");
			                    bd2.setSwitchBj2("2000");
			                    basicAddressService.add(bd2);
							} else {
								bd2.setId(addressResult.getId());
								basicAddressService.update(bd2);
							}
						} else {
				            bd.setUnitType("门店");
							basicPutgoodsService.save(bd);
			                bd2.setPutgoodsId(Long.parseLong(bd.getId().toString()));
		                	bd2.setPutgoodsName(name);
		                	bd2.setLongitude("0");
		                    bd2.setLatitude("0");
			                bd2.setSwitchWl("1");
			                bd2.setSwitchBj("1500");
			                bd2.setSwitchBj2("2000");
			                basicAddressService.add(bd2);
						}
					}
				}
			}
		}
		return ResponseData.success();
    }
	
	@Autowired
    private BasicAddressService basicAddressService;
    
    /**
     * 下载模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcel")
    public void downloadExcel(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/putgoods.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("Unit Address Template" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 下载模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelupdate")
    public void downloadExcelupdate(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/putgoods_update.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("Unit Address Update Template" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 下载模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelhx")
    public void downloadExcelhx(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/putgoods_hx.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("Retail Unit File Import Template" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入excel   
     */
	@RequestMapping(value = "/importExcel" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file,  BasicPutgoodsParam basicPutgoodsParam)  {
		ResponseData data = new ResponseData();
		try {
			data = basicPutgoodsService.getExceldata(file,basicPutgoodsParam,data);//处理导入数据
		} catch (Exception e) {
			data.setSuccess(false);
			e.printStackTrace();
		}
        return data;
    }

    /**
     * 导入excel   
     */
	@RequestMapping(value = "/importExcelupdate" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodlupdate(@RequestPart("file") MultipartFile file,  BasicPutgoodsParam basicPutgoodsParam)  {
		ResponseData data = new ResponseData();
		try {
			data = basicPutgoodsService.getExceldataupdate(file,basicPutgoodsParam,data);//处理导入数据
		} catch (Exception e) {
			data.setSuccess(false);
			e.printStackTrace();
		}
        return data;
    }

    /**
     * 导入excel   
     */
	@RequestMapping(value = "/importExcelhx" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodlhx(@RequestPart("file") MultipartFile file,  BasicPutgoodsParam basicPutgoodsParam)  {
		ResponseData data = new ResponseData();
		try {
			data = basicPutgoodsService.getExceldatahx(file,basicPutgoodsParam,data);//处理导入数据
		} catch (Exception e) {
			data.setSuccess(false);
			e.printStackTrace();
		}
        return data;
    }

    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BasicPutgoodsParam basicPutgoodsParam) {
    	String putgoodsName = basicPutgoodsParam.getPutgoodsName();
    	if (putgoodsName!=null&&putgoodsName!="") {
    		putgoodsName = putgoodsName.replace("& #40;", "(");
    		putgoodsName = putgoodsName.replace("& #41;", ")");
    		basicPutgoodsParam.setPutgoodsName(putgoodsName);
    	}
        Object putgoodsCustomerId = basicPutgoodsParam.getPutgoodsCustomerId();
        if (putgoodsCustomerId != null){
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(putgoodsCustomerId.toString()));
            basicPutgoodsParam.setPutgoodsOperateName(basicCustomer.getCustomerName());
        }
        
        basicPutgoodsParam.setDeliverId(userService.getDeliverId());
        basicPutgoodsParam.setDeptId(userService.getDeptId());
        
        BasicPutgoodsParam param = new BasicPutgoodsParam();
        param.setPutgoodsCustomerId(basicPutgoodsParam.getPutgoodsCustomerId());
        param.setPutgoodsName(basicPutgoodsParam.getPutgoodsName());
        BasicPutgoodsResult result = basicPutgoodsService.findBySpec(param,null);
        if(result != null) {
        	return ResponseData.error("This customer name already exists!");
        }
        this.basicPutgoodsService.add(basicPutgoodsParam);
        return ResponseData.success();
    }

    /**
     * 新增接口
     */
    @RequestMapping("/addItemhx")
    @ResponseBody
    public ResponseData addItemhx(BasicPutgoodsParam basicPutgoodsParam) {
    	String putgoodsName = basicPutgoodsParam.getPutgoodsName();
    	if (putgoodsName!=null&&putgoodsName!="") {
    		putgoodsName = putgoodsName.replace("& #40;", "(");
    		putgoodsName = putgoodsName.replace("& #41;", ")");
    		basicPutgoodsParam.setPutgoodsName(putgoodsName);
    	}
        Object putgoodsCustomerId = basicPutgoodsParam.getPutgoodsCustomerId();
        if (putgoodsCustomerId != null){
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(putgoodsCustomerId.toString()));
            basicPutgoodsParam.setPutgoodsOperateName(basicCustomer.getCustomerName());
        }
        
        basicPutgoodsParam.setDeliverId(userService.getDeliverId());
        basicPutgoodsParam.setDeptId(userService.getDeptId());
        
        BasicPutgoodsParam param = new BasicPutgoodsParam();
        param.setPutgoodsCustomerId(basicPutgoodsParam.getPutgoodsCustomerId());
        param.setPutgoodsName(basicPutgoodsParam.getPutgoodsName());
        BasicPutgoodsResult result = basicPutgoodsService.findBySpec(param,null);
        if(result != null) {
        	return ResponseData.error("This customer name already exists!");
        }
        this.basicPutgoodsService.add(basicPutgoodsParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BasicPutgoodsParam basicPutgoodsParam) {
    	String putgoodsName = basicPutgoodsParam.getPutgoodsName();
    	if (putgoodsName!=null&&putgoodsName!="") {
    		putgoodsName = putgoodsName.replace("& #40;", "(");
    		putgoodsName = putgoodsName.replace("& #41;", ")");
    		basicPutgoodsParam.setPutgoodsName(putgoodsName);
    	}
        Object putgoodsCustomerId = basicPutgoodsParam.getPutgoodsCustomerId();
        if (putgoodsCustomerId != null){
            BasicCustomer basicCustomer = basicCustomerService.getById(Integer.parseInt(putgoodsCustomerId.toString()));
            basicPutgoodsParam.setPutgoodsOperateName(basicCustomer.getCustomerName());
        }
        this.basicPutgoodsService.update(basicPutgoodsParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    @Permission
    public ResponseData delete(BasicPutgoodsParam basicPutgoodsParam) {
        this.basicPutgoodsService.delete(basicPutgoodsParam);
        return ResponseData.success();
    }

    /**
     * 计算配送总直线距离
     */
    @RequestMapping("/zongzhixian")
    @ResponseBody
    public ResponseData zongzhixian(BasicPutgoodsParam basicPutgoodsParam) {
    	if(basicPutgoodsParam.getPutgoodsCustomerId() == null) {
            return ResponseData.error("Please Select Customer");
    	}
    	double zong = 0;
    	BasicPutgoodsParam fa = new BasicPutgoodsParam();
    	fa.setPutgoodsCustomerId(basicPutgoodsParam.getPutgoodsCustomerId());
    	fa.setUnitCategory("发货");
    	BasicPutgoodsResult far = basicPutgoodsService.findBySpec(fa, null);
    	if(far == null) {
            return ResponseData.error("Please set delivery unit");
    	}
    	BasicAddressParam basicAddressParam = new BasicAddressParam();
    	basicAddressParam.setPutgoodsId(Long.parseLong(far.getId().toString()));
    	BasicAddressResult addressResult = basicAddressService.findBySpec(basicAddressParam);
    	if(addressResult == null) {
    		return ResponseData.error("Loading address does not exist! Please maintain");
    	}
    	List<BasicPutgoodsResult> list = basicPutgoodsService.findListBySpecjinweidu(basicPutgoodsParam);
    	for (BasicPutgoodsResult r : list) {
			if(ToolUtil.isNotEmpty(addressResult.getLongitude())&&ToolUtil.isNotEmpty(addressResult.getLatitude())) {
				if(!addressResult.getLongitude().equals("0")&&!addressResult.getLatitude().equals("0")) {
					if(ToolUtil.isNotEmpty(r.getLongitude())&&ToolUtil.isNotEmpty(r.getLatitude())) {
						if(!r.getLongitude().equals("0")&&!r.getLatitude().equals("0")) {
							double a = MapUtils.GetDistance(Double.parseDouble(r.getLongitude()), Double.parseDouble(r.getLatitude()), Double.parseDouble(addressResult.getLongitude()), Double.parseDouble(addressResult.getLatitude()));
							zong += a;
//							if(ToolUtil.isEmpty(r.getKilometer())) {
//								BasicAddressParam update = new BasicAddressParam();
//								update.setId(r.getAid());
//								update.setKilometer(a/1000+"");
//								basicAddressService.update(update);
//							}
						}
					}
				}
			}
    		
		}
        return ResponseData.success(zong);
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BasicPutgoodsParam basicPutgoodsParam) {
        BasicPutgoods detail = this.basicPutgoodsService.getById(basicPutgoodsParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BasicPutgoodsParam basicPutgoodsParam,String condition) {
    	if (condition!=null&&condition!="") {
    		condition = condition.replace("& #40;", "(");
    		condition = condition.replace("& #41;", ")");
    	}
    	User user = userService.getcurrentUser();
        basicPutgoodsParam.setDeliverId(user.getDeliverId());
        Long deptId = user.getDeptId();


		String roleId = user.getRoleId();
		if(ToolUtil.isNotEmpty(roleId)){
			for(String rId : roleId.split(",")){
				Role byId = roleService.getById(rId);
				if(byId != null && byId.getName().contains("承运商")){
					BasicCarrierParam param = new BasicCarrierParam();
					param.setUserId(user.getUserId());
					BasicCarrierResult bySpec = basicCarrierService.findBySpec(param, user.getOperateId());
					if(bySpec != null){
						basicPutgoodsParam.setCarrierId(bySpec.getId());
					}else{
						basicPutgoodsParam.setCarrierId(-1);
					}
				}
			}
		}
        return this.basicPutgoodsService.findPageBySpec(basicPutgoodsParam,condition,deptId,user.getOperateId());
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/listnew")
    public LayuiPageInfo listnew(BasicPutgoodsParam basicPutgoodsParam,String condition) {
    	if (condition!=null&&condition!="") {
    		condition = condition.replace("& #40;", "(");
    		condition = condition.replace("& #41;", ")");
    	}
    	User user = userService.getcurrentUser();
        basicPutgoodsParam.setDeliverId(user.getDeliverId());
        Long deptId = user.getDeptId();
        return this.basicPutgoodsService.findPageNewBySpec(basicPutgoodsParam,condition,deptId,user.getOperateId());
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list_hx")
    public LayuiPageInfo list_hx(BasicPutgoodsParam basicPutgoodsParam,String condition) {
		if (condition != null && !condition.isEmpty()) {
			condition = condition.replace("& #40;", "(");
			condition = condition.replace("& #41;", ")");
		}
    	User user = userService.getcurrentUser();
    	if(ToolUtil.isEmpty(basicPutgoodsParam.getUnitType())) {
    		basicPutgoodsParam.setUnitType("门店");
    	}
        basicPutgoodsParam.setDeliverId(user.getDeliverId());
        Long deptId = user.getDeptId();
        return this.basicPutgoodsService.findPageBySpecHx(basicPutgoodsParam,condition,deptId,user.getOperateId());
    }
    
    /**
     * 导出Excel
     */
    @RequestMapping("/exportExcelBySpec")
    public void exportExcelBySpec(HttpServletResponse response, BasicPutgoodsParam basicPutgoodsParam,String condition) throws IOException {
        Workbook wb = basicPutgoodsService.exportToExcel(basicPutgoodsParam,condition);
        OutputStream output = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("Delivery Unit Address Information" + ".xlsx").getBytes(), "iso-8859-1"));
        wb.write(output);
        output.close();
    }
	/**
	 * 仓库绑定门店页面
	 */
	@RequestMapping("/bindPutgoods")
	public String bindPutgoods(Model model,String warehouseId) {
		BasicPutgoodsParam basicPutgoodsParam = new BasicPutgoodsParam();
		User user = userService.getcurrentUser();
		BasicWarehouse byId = this.warehouseService.getById(warehouseId);
		if(ToolUtil.isEmpty(basicPutgoodsParam.getUnitType())) {
			basicPutgoodsParam.setUnitType("门店");
		}
		basicPutgoodsParam.setDeliverId(user.getDeliverId());
		Long deptId = user.getDeptId();
		basicPutgoodsParam.setDeptId(deptId);
		List<BasicPutgoodsResult> pageBySpec = this.basicPutgoodsService.findListBySpec(basicPutgoodsParam, user.getOperateId());

		model.addAttribute("warehouseId", warehouseId);
		model.addAttribute("warehouseName", byId.getWarehouseName());
		model.addAttribute("putgoods", pageBySpec);
		return PREFIX + "/index_clm_add.html";
	}


	/**
	 * 仓库绑定门店逻辑
	 */
	@RequestMapping("/warehouseBindPutgoods")
	@ResponseBody
	public ResponseData warehouseBindPutgoods(String storeId,String warehouseId) {
		List<BasicPutgoodsResult> pageBySpec = this.warehouseStoreService.findByStoreIdAndWarehouseId(storeId, warehouseId);
		if(pageBySpec.size() > 0) {
			return ResponseData.error("This warehouse has already bound a store!");
		}
		User userAop = userService.getcurrentUser();
		WarehouseStoreParam warehouseStoreParam = new WarehouseStoreParam();
		warehouseStoreParam.setStoreId(Integer.valueOf(storeId));
		warehouseStoreParam.setWarehouseId(Integer.valueOf(warehouseId));
		warehouseStoreParam.setCreateUser( userAop.getUserId());
		warehouseStoreParam.setCreateTime(new Date());
		warehouseStoreService.add(warehouseStoreParam);

		return ResponseData.success();
	}

	/**
	 * 根据仓库id查询门店
	 */
	@RequestMapping("/getStoreByWarehouseId")
	@ResponseBody
	public LayuiPageInfo getStoreByWarehouseId(String warehouseId) {

		LayuiPageInfo layuiPageInfo = this.basicPutgoodsService.getStoreByWarehouseId( warehouseId);

		return layuiPageInfo;
	}

	/**
	 * 解绑门店
	 */
	@RequestMapping("/onUnbind")
	@ResponseBody
	public ResponseData onUnbind(String storeId,String warehouseId) {
		this.basicPutgoodsService.unBindStoreByWarehouseId( storeId, warehouseId);
		return ResponseData.success();
	}
}


